/***************************************************
 ** @Desc : This file for 发送请求并判断是否已经注册
 ** @Time : 2019.01.08 15:21 
 ** @Author : Joker
 ** @File : is_regist
 ** @Last Modified by : Joker
 ** @Last Modified time: 2019.01.08 15:21
 ** @Software: GoLand
****************************************************/
package controllers

import (
	"github.com/astaxie/beego"
	"regexp"
	"your_regist/controllers/utils"
	"time"
	"strconv"
	"sort"
	"bytes"
	"your_regist/models"
	"strings"
	utils2 "your_regist/utils"
	"encoding/json"
	"fmt"
	"math/rand"
)

type IsRegist struct {
	beego.Controller
}

var log = utils2.Log{}

//主方法
//@router /regist.py/?:params [post,get]
func (this *IsRegist) SendMsgIsRegist() {
	utc1 := time.Now().Unix()
	phone := this.GetString("phone")
	if phone == "" {
		this.Ctx.WriteString("手机号或邮箱不能为空")
	}

	req_method := utils.RequestMethod{}
	siteInfo := models.SiteInfo{}
	siteInfos := siteInfo.SelectAllRegisterInfo()

	registed_site := make([]utils.RegistedSite, len(siteInfos))
	if !this.isPhone(phone) && !this.isEmail(phone) {
		this.Ctx.WriteString("请输入正确的手机号或邮箱")
	} else {
		count := 0
		for _, v := range siteInfos {
			//新浪网
			if strings.Compare("XinLang", v.EnName) == 0 {
				unix := strconv.FormatInt(time.Now().Unix(), 10)

				xinLangReq_map := make(map[string]string)
				if this.isEmail(phone) {
					xinLangReq_map = map[string]string{
						"type":  "email",
						"value": phone,
						"__rnd": unix,
					}
				}

				if this.isPhone(phone) {
					xinLangReq_map = map[string]string{
						"type":  "mobilesea",
						"zone":  "0086",
						"value": phone,
						"__rnd": unix,
					}
				}

				xinLang_params := this.toStringByMapRemoveChar(xinLangReq_map)
				url_data := v.ReqAddr + "?" + xinLang_params

				resp_xinlang, err := req_method.XinLangHttpGetRequest(url_data, v.Cookie)
				if err != nil {
					log.LogError(resp_xinlang, err)
					continue
				} else {
					xinLangResp := utils.XinLangResp{}
					err = json.Unmarshal([]byte(resp_xinlang), &xinLangResp)
					if err != nil {
						log.LogError("XinLang response data format is error:", err)
						continue
					}

					//已经注册
					if strings.Compare("600001", xinLangResp.Code) == 0 {
						registed_site[count].SiteName = v.CnName
						registed_site[count].SiteAddress = v.HomeUrl
					}
				}
				//只需要判断一个,后面则不需要判断
				continue
			}

			//学信网
			if strings.Compare("XueXin", v.EnName) == 0 {
				if this.isPhone(phone) {
					xueXinReq_map := map[string]string{
						"mphone":   phone,
						"dataInfo": phone,
						"optType":  "REGISTER",
					}

					xueXin_params := this.toStringByMapRemoveChar(xueXinReq_map)
					url_data := v.ReqAddr + "?" + xueXin_params

					resp_xueXin, err := req_method.HttpGetRequest(url_data)
					if err != nil {
						log.LogError(resp_xueXin, err)
						continue
					} else {
						xueXin_resp := this.removeExtraChar(resp_xueXin)

						//已经注册
						if strings.Compare("false", xueXin_resp) == 0 {
							registed_site[count].SiteName = v.CnName
							registed_site[count].SiteAddress = v.HomeUrl
						}
					}
				}
				continue
			}

			//虎牙直播
			if strings.Compare("HuYa", v.EnName) == 0 {
				if this.isPhone(phone) {
					tel := map[string]string{
						"phone": phone,
					}
					req_Id := rand.Intn(100000000)
					huYaReq_map := map[string]interface{}{
						"uri":       "60003",
						"version":   "2.2",
						"context":   v.Cookie,
						"appId":     "5002",
						"lcid":      fmt.Sprintf("%d", rand.Intn(10000)),
						"byPass":    "3",
						"sdid":      fmt.Sprintf("%d", rand.Intn(100000000)),
						"requestId": fmt.Sprintf("%d", req_Id),
						"data":      tel,
					}
					huYa_params, _ := json.Marshal(huYaReq_map)

					resp_huYa, err := req_method.HuYaHttpPostRequest(v.ReqAddr, string(huYa_params))
					if err != nil {
						log.LogError(resp_huYa, err)
						continue
					} else {
						huYa_resp := utils.HuYaResp{}
						err = json.Unmarshal([]byte(resp_huYa), &huYa_resp)
						if err != nil {
							log.LogError("HuYa response data format is error:", err)
							continue
						}

						//已经注册
						if strings.Compare("MOBILE_HAS_REGISTER", huYa_resp.Message) == 0 {
							registed_site[count].SiteName = v.CnName
							registed_site[count].SiteAddress = v.HomeUrl
						}
					}
				}
				continue
			}
			count++
		}
	}

	utc2 := time.Now().Unix()
	fmt.Println("耗时：", utc2-utc1, "秒")

	fmt.Println(registed_site)
	this.Ctx.WriteString(fmt.Sprintf("查询注册: %s; 耗时: %ds", registed_site, utc2-utc1))

	this.StopRun()
}

//剔除响应数据中的多余字符
func (*IsRegist) removeExtraChar(original_data string) string {
	return strings.Replace(original_data, "\r\n", "", -1)
}

//是否为正确邮箱
func (*IsRegist) isEmail(b string) bool {
	emailPattern := regexp.MustCompile("\\w[-\\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\\.)+[A-Za-z]{2,14}")
	return emailPattern.Match([]byte(b))
}

//是否为正确手机号
func (*IsRegist) isPhone(b string) bool {
	phonePattern := regexp.MustCompile("^[1]([3-9])[0-9]{9}$")
	return phonePattern.Match([]byte(b))
}

//将map拼接成字符串,去掉最后一个&符号
func (*IsRegist) toStringByMapRemoveChar(m map[string]string) (s string) {
	//键排序
	keys := make([]string, 0)
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	//连接键值对
	var buffer bytes.Buffer
	for i := 0; i < len(m); i++ {
		if m[keys[i]] == "" { //剔除值为空的参数
			continue
		}
		buffer.WriteString(keys[i])
		buffer.WriteString("=")
		buffer.WriteString(m[keys[i]])
		buffer.WriteString("&")
	}
	buf := buffer.String()
	return string([]byte(buf)[:len(buf)-1])
}

func (*IsRegist) toStringByMapRemoveCharV2(m map[string]interface{}) (s string) {
	//键排序
	keys := make([]string, 0)
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	//连接键值对
	var buffer bytes.Buffer
	for i := 0; i < len(m); i++ {
		//是否为string类型
		if _, ok := m[keys[i]].(string); ok {
			if m[keys[i]] == "" { //剔除值为空的参数
				continue
			}
			buffer.WriteString(keys[i])
			buffer.WriteString("=")
			buffer.WriteString(m[keys[i]].(string))
			buffer.WriteString("&")
		} else {

		}

	}
	buf := buffer.String()
	return string([]byte(buf)[:len(buf)-1])
}
